<?php
define('GC_DEBUG', false);
class Shangku_GlobalCollect_IndexController extends Mage_Core_Controller_Front_Action
{
	private function _initOrder()
	{
		$orderIncrementId =Mage::getSingleton('checkout/session')->getLastRealOrderId();
		$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
		
		if(!$order->getId()){
			return false;
		}
		
		return $order;
	}
	protected  function _getSession()
	{
		return Mage::getSingleton('core/session');
	}
	public function addressSaveAction()
	{
		$addressId  = $this->getRequest()->getPost('address_id');
		$address    = Mage::getModel('sales/order_address')->load($addressId);
		$data       = $this->getRequest()->getPost('billing');
		if ($data && $address->getId()) {
			$address->addData($data);
			try {
				$address->implodeStreetAddress()
					->save();
				$this->_getSession()->addSuccess(Mage::helper('sales')->__('The order address has been updated.'));
			} catch (Mage_Core_Exception $e) {
				$this->_getSession()->addError($e->getMessage());
			} catch (Exception $e) {
				$this->_getSession()->addException(
						$e,
						Mage::helper('sales')->__('An error occurred while updating the order address. The address has not been changed.')
				);
			}
			$this->_redirect('*/*/redirect', array('_secure'=>true));
		} else {
			$this->_redirect('checkout/cart/index');
		}
	}
	public function redirectAction()
	{
		if($order = $this->_initOrder()){
			Mage::register('current_global_collect_order', $order);
			
			$session = Mage::getSingleton('checkout/session');
			$session->setGlobalCollectQuoteId($session->getQuoteId());

			$this->loadLayout();
			$this->renderLayout();
			
			$session->unsQuoteId();
			$session->unsRedirectUrl();
		} else {
			$this->_redirect('checkout/cart/index');
			return;
		}
		
	}
	
	public function checkoutProcessAction()
	{
		//increment_id
		$orderId = $this->getRequest()->getPost('orderId', 0);
		$paymentId = $this->getRequest()->getPost('paymentId', 0);
		
		$result = array();
		if(!$orderId || !$paymentId){
			$result['error'] = 'true';
			$result['errorMsg'] = $this->__('error params!');
		} else {
			$api = Mage::getModel('globalcollect/api');
			$response = $api->call('INSERT_ORDERWITHPAYMENT', $orderId, $paymentId);
			if(!$response){
				$result['error'] = 'true';
				$result['errorMsg'] = $this->__('something error!');
			} else {
				$response = $response->REQUEST->RESPONSE;
				if('OK' == (string)$response->RESULT){
					$result['error'] = 'false';
					$result['src'] = (string)$response->ROW->FORMACTION;
				} else {
					$result['error'] = 'true';
					$result['errorMsg'] = $this->__('something error!');
					if(defined('GC_DEBUG') && GC_DEBUG == true){
						$debuInfo = Zend_Debug::dump($response, null, false);
						$result['response'] = $debuInfo;
					}
				}
			}
		}
		
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}
	public function successAction()
	{
		$success = $this->_checkPayStaus();
		if($success){
			$session = Mage::getSingleton('checkout/session');
			$session->setQuoteId($session->getGlobalCollectQuoteId(true));
			Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
			$successUrl = Mage::getUrl('checkout/onepage/success', array('_secure'=>true));
		} else {
			$errorMsg = $this->__('We’re sorry, we weren’t able to confirm your card information. If your information was entered correctly and you’re still having trouble, try paying with your credit or debit card through PayPal. For assistance, please contact us through Live Chat.');
			Mage::getSingleton('core/session')->addError($errorMsg);
			$successUrl = Mage::getUrl('globalcollect/index/redirect', array('_secure'=>true));
		}
		
		$jumpScript = "<script>window.parent.location.href = '{$successUrl}'</script>";
		$this->getResponse()->setBody($jumpScript);
	}
	
	private function _checkPayStaus()
	{
		if($order = $this->_initOrder()){
			$api = Mage::getModel('globalcollect/api');
			$response = $api->call('GET_ORDERSTATUS', $order->getIncrementId());
			if(!$response){
				return false;
			} else {
				$response = $response->REQUEST->RESPONSE;
				if(defined('GC_DEBUG') && GC_DEBUG == true){
					$debuInfo = Zend_Debug::dump($response, null, false);
					Mage::getSingleton('core/session')->addNotice($debuInfo);
				}
				if('OK' == (string)$response->RESULT){
					if((string)$response->STATUS->STATUSID >= 800){
						$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, Mage_Sales_Model_Order::STATE_PROCESSING, $this->__('globalcollect pay success!'))
						->save();;
						return true;
					}
				}
			}
		}
		
		return false;
	}
}
